package nettyclient;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.concurrent.FutureListener;
import ui.AbstractFrame;

/**
 * @author Hujf
 * @title: NettyInit
 * @date 2021/2/15 0015下午 7:52
 * @description: TODO
 */
public class NettyInit {
    public static SocketChannel socketChannel;
    public SocketChannel getSocketChannel() {
        return socketChannel;
    }
    public  void init(String s1, String s2, int code,AbstractFrame n ){
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();

        try{
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast("encoder",new StringEncoder());
                            pipeline.addLast("decoder",new StringDecoder());
                            pipeline.addLast(new ClientRegesterHandler(s1,s2,code,n));
                        }
                    });
            ChannelFuture sync = bootstrap.connect("127.0.0.1", 8002);
            sync.addListener((ChannelFutureListener) future -> {
                socketChannel = (SocketChannel) future.channel();
                System.out.println(socketChannel.isActive());
                if (future.isSuccess()) { //成功连接
                    System.out.println("成功连接");
                }
            });
            sync.sync();
            System.out.println(socketChannel.isActive());
//            sync.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
          //  eventLoopGroup.shutdownGracefully();
        }
    }

    public  void frameInit(String s1, String s2, int code, AbstractFrame n) {
        init(s1,s2,code,n);
    }
}
